package com.leyou.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.constants.MQConstants;
import com.leyou.common.dto.PageResult;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.item.dto.*;
import com.leyou.item.entity.Sku;
import com.leyou.item.entity.Spu;
import com.leyou.item.entity.SpuDetail;
import com.leyou.item.mapper.SkuMapper;
import com.leyou.item.mapper.SpuDetailMapper;
import com.leyou.item.mapper.SpuMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 虎哥
 */
@Service
public class GoodsService {

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private SpuDetailMapper detailMapper;

    public PageResult<SpuDTO> querySpuByPage(String key, Integer page, Integer rows, Boolean saleable) {
        // 1.分页查询
        PageHelper.startPage(page, rows);
        // 2.搜索条件
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        // 2.1.关键字过滤
        if (StringUtils.isNotBlank(key)) {
            criteria.andLike("name", "%" + key + "%");
        }
        // 2.2.上下架过滤
        if (saleable != null) {
            criteria.andEqualTo("saleable", saleable);
        }
        // 3.排序
        example.orderBy("updateTime").desc();
        // 4.查询数据
        List<Spu> list = spuMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(list)) {
            throw new LyException(ExceptionEnum.RESOURCE_NOT_FOUND);
        }
        // 5.封装结果
        // 5.1.分页结果
        PageInfo<Spu> info = new PageInfo<>(list);
        // 5.2.DTO转换
        List<SpuDTO> dtoList = BeanHelper.copyWithCollection(list, SpuDTO.class);
        // 5.3.查询分类和品牌的名称
        handleCategoryAndBrandName(dtoList);
        return new PageResult<>(info.getTotal(), info.getPages(), dtoList);
    }

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    private void handleCategoryAndBrandName(List<SpuDTO> dtoList) {
        for (SpuDTO spu : dtoList) {
            // 查询品牌
            BrandDTO brandDTO = brandService.queryById(spu.getBrandId());
            spu.setBrandName(brandDTO.getName());
            // 查询三级分类
            String name = categoryService.queryByIds(spu.getCategoryIds())
                    .stream()
                    .map(CategoryDTO::getName)
                    .collect(Collectors.joining("/"));
            spu.setCategoryName(name);
        }
    }

    @Autowired
    private SkuMapper skuMapper;

    @Transactional
    public void saveGoods(SpuDTO spuDTO) {
        Spu spu = BeanHelper.copyProperties(spuDTO, Spu.class);
        // 默认下架
        spu.setSaleable(false);
        // 1.写Spu
        spuMapper.insertSelective(spu);

        // 2.写SpuDetail
        SpuDetail detail = BeanHelper.copyProperties(spuDTO.getSpuDetail(), SpuDetail.class);
        detail.setSpuId(spu.getId());
        detailMapper.insertSelective(detail);

        // 3.写Sku
        spuDTO.setId(spu.getId());
        saveSku(spuDTO);

         /*List<Sku> list = new ArrayList<>();
        for (SkuDTO skuDTO : skus) {
            Sku sku = BeanHelper.copyProperties(skuDTO, Sku.class);
            sku.setSpuId(spu.getId());
            // 默认下架
            sku.setEnable(false);
            list.add(sku);
        }*/
    }

    private void saveSku(SpuDTO spuDTO) {
        List<SkuDTO> skuDTOList = spuDTO.getSkus();

        List<Sku> skuList = skuDTOList.stream()
                .map(skuDTO -> {
                    Sku sku = BeanHelper.copyProperties(skuDTO, Sku.class);
                    sku.setSpuId(spuDTO.getId());
                    // 默认下架
                    sku.setEnable(false);
                    return sku;
                }).collect(Collectors.toList());

        skuMapper.insertList(skuList);
    }

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Transactional
    public void updateSaleable(Long id, Boolean saleable) {
        // 修改spu表 update tb_spu set saleable = 1 where id = 1
        Spu spu = new Spu();
        spu.setSaleable(saleable);
        spu.setId(id);
        int count = spuMapper.updateByPrimaryKeySelective(spu);
        if (count != 1) {
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }
        // 修改sku表 update tb_sku set enable = 1 where spu_id = 1
        // 要修改的数据
        Sku sku = new Sku();
        sku.setEnable(saleable);
        // 修改时的where条件
        Example example = new Example(Sku.class);
        example.createCriteria().andEqualTo("spuId", id);
        count = skuMapper.updateByExampleSelective(sku, example);
        if (count < 1) {
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }

        // 发送mq
        String routingKey = saleable ? MQConstants.RoutingKey.ITEM_UP_KEY : MQConstants.RoutingKey.ITEM_DOWN_KEY;
        amqpTemplate.convertAndSend(MQConstants.Exchange.ITEM_EXCHANGE_NAME, routingKey, spu.getId());
    }

    public SpuDTO querySpuById(Long spuId) {
        // 1.查询spu
        Spu spu = spuMapper.selectByPrimaryKey(spuId);
        if (spu == null) {
            throw new LyException(ExceptionEnum.RESOURCE_NOT_FOUND);
        }
        SpuDTO spuDTO = BeanHelper.copyProperties(spu, SpuDTO.class);

        // 2.查询spuDetail
        SpuDetailDTO spuDetail = querySpuDetailBySpuId(spuId);
        spuDTO.setSpuDetail(spuDetail);

        // 3.查询sku
        List<SkuDTO> skuList = querySkuBySpuId(spuId);
        spuDTO.setSkus(skuList);
        return spuDTO;
    }

    public List<SkuDTO> querySkuBySpuId(Long spuId) {
        Sku sku = new Sku();
        sku.setSpuId(spuId);
        List<Sku> list = skuMapper.select(sku);
        if(CollectionUtils.isEmpty(list)){
            throw new LyException(ExceptionEnum.RESOURCE_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(list, SkuDTO.class);
    }

    public SpuDetailDTO querySpuDetailBySpuId(Long spuId) {
        SpuDetail spuDetail = detailMapper.selectByPrimaryKey(spuId);
        if (spuDetail == null) {
            throw new LyException(ExceptionEnum.RESOURCE_NOT_FOUND);
        }
        return BeanHelper.copyProperties(spuDetail, SpuDetailDTO.class);
    }

    @Transactional
    public void updateGoods(SpuDTO spuDTO) {
        // 1.修改spu
        Spu spu = BeanHelper.copyProperties(spuDTO, Spu.class);
        // 把不需要修改的字段设置为null，不会被修改了。
        spu.setSaleable(null);
        int count = spuMapper.updateByPrimaryKeySelective(spu);
        if(count == 0){
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }
        // 2.修改spuDetail
        SpuDetail detail = BeanHelper.copyProperties(spuDTO.getSpuDetail(), SpuDetail.class);
        count = detailMapper.updateByPrimaryKeySelective(detail);
        if(count == 0){
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }
        // 3.删除sku
        Sku sku = new Sku();
        sku.setSpuId(spuDTO.getId());
        int size = skuMapper.selectCount(sku);
        if(size > 0) {
            count = skuMapper.delete(sku);
            if (count != size) {
                throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
            }
        }
        // 4.新增sku
        saveSku(spuDTO);
    }

    public List<SkuDTO> querySkuByIds(List<Long> ids) {
        List<Sku> list = skuMapper.selectByIdList(ids);
        if(CollectionUtils.isEmpty(list)){
            throw new LyException(ExceptionEnum.RESOURCE_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(list, SkuDTO.class);
    }

    @Transactional
    public void minusStock(Map<Long, Integer> skuMap) {
        for (Map.Entry<Long, Integer> entry : skuMap.entrySet()) {
            // 更新
            try {
                skuMapper.minusStock(entry.getKey(), entry.getValue());
            } catch (Exception e) {
                throw new LyException(ExceptionEnum.STOCK_NOT_ENOUGH, e);
            }
        }
    }

    @Transactional
    public void plusStock(Map<Long, Integer> skuMap) {
        for (Map.Entry<Long, Integer> entry : skuMap.entrySet()) {
            // 更新
            try {
                skuMapper.plusStock(entry.getKey(), entry.getValue());
            } catch (Exception e) {
                throw new LyException(ExceptionEnum.STOCK_NOT_ENOUGH, e);
            }
        }
    }
}
